package com.gupaoedu.pattern.singleton.destroy;

import java.io.*;

/**
 * 2019/5/11
 * created by chenpp
 * 反序列化确实可以破坏单例,在调用readObject的时候先根据是否有无参构造方法初始化一次实例，
 * 然后判断是否有readResolve方法,如果有的话,将其invoke的执行结果返回，然后赋值给返回的变量
 * 缺点:实际在jvm层进行了两次单例的初始化，还是会有内存浪费的情形
 */

public class SeriableSingletonTest {
    public static void main(String[] args) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            ObjectOutputStream oos = new ObjectOutputStream(out);
            SeriableSingleton instance1 = SeriableSingleton.getInstance();
            oos.writeObject(instance1);
            oos.close();
            ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(ios);
            SeriableSingleton instance =(SeriableSingleton) ois.readObject();
            System.out.println(instance1);
            System.out.println(instance);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }

    }
}
